package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: Rodgers
 * @Date 2022/3/17 10:16
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 添加购物车
     *
     * @param shoppingCart 前端传递过来的购物车数据
     * @return ShoppingCart 返回添加成功后的购物车数据
     */
    @Override
    public ShoppingCart addCart(ShoppingCart shoppingCart) {
        //1.判断当前加入的菜品或套餐在当前用户的购物车数据记录中是否含有这个数据
        ShoppingCart dbShoppingCart = shoppingCartMapper.findByShoppingCart(shoppingCart);
        if (dbShoppingCart!=null){
            //2.如果有，数量+1，调用mapper更新数量
            dbShoppingCart.setNumber(dbShoppingCart.getNumber() +1);
            shoppingCartMapper.updateNumber(dbShoppingCart.getId(), dbShoppingCart.getNumber());
        }
        else {
            //3.如果没有，调用mapper新增一条购物车记录数据
            //完善创建时间
            dbShoppingCart = shoppingCart;
            dbShoppingCart.setCreateTime(LocalDateTime.now());
            //完善数量
            dbShoppingCart.setNumber(1);

            //新增插入
            shoppingCartMapper.save(dbShoppingCart);
        }

        return dbShoppingCart;
    }

    /**
     * 查询指定用户的购物车集合数据
     *
     * @param userId 用户id
     * @return List 返回购物车集合数据
     */
    @Override
    public List<ShoppingCart> findAllByUserId(Long userId) {
        return shoppingCartMapper.findAllByUserId(userId);
    }

    /**
     * 清空购物车
     *
     * @param userId
     */
    @Override
    public void clean(Long userId) {
        shoppingCartMapper.deleteByUserId(userId);
    }
}
